//获取工站物料架
function getAllRackInfo() {
    let url = `http://${ipValue}:55200/v1/materialRack/getAll`,
        arr = []
    $.ajax({
        url,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        async: !workInfo,
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                arr = res.msg
            }else{
				backErr(res.msg)
			}
        },
        timeout: timeOut,
        error: () => {
            // overTime()
        }
    })
    return arr
}

function popPickerWorkstation(index) {
    var picker = new mui.PopPicker();
    let arr = [],
        data = getWorkstation()
    if (data && data.length) {
        data.map(item => {
            arr.push({
                value: item.siteName,
                text: item.name
            })
        })
    } else {
        arr.push({
            value: 0,
            text: '暂无工站'
        })
    }

    picker.setData(arr)
    picker.show(function (SelectedItem) {
        if (index == 1) {
            if (SelectedItem[0].value) {
                workstation = SelectedItem[0].text
                localStorage.setItem('workstation', workstation);
                $(".tips-box .workstation").text(workstation)
                getWorkstationSite()
                workSite()
            } else {
            }
        } else if (index == 2) {
            if (SelectedItem[0].value) {
                $('.select-next input').val(SelectedItem[0].text)
            } else {
            }
        }
        getInfo()
    })

}

function getWorkstation() {
    let data = [],
        url = `http://${ipValue}:55200/v1/workstation/getAll`
    $.ajax({
        url,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        async: !workInfo,
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                data = res.msg
                // data.map(item=>{
                //     if (item.plateNumber === plateNumber){
                //
                //     }
                // })
            }else{
				backErr(res.msg)
			}
        },
        timeout: timeOut,
        error: () => {
            // overTime()
        }

    })
    return data
}

//获取所有车辆信息
function getVehiclesinfo() {
    let data = [],
        id = ''
    id = localStorage.getItem('sessionId')
    $.ajax({
        url: `http://${ipValue}:55200/v1/vehiclesinfo`,
        contentType: "application/json;charset=utf-8",
        data: '',
        type: "get",
        async: !workInfo,
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                data = res.msg
            } else {
                toastText(res.msg)
            }
        },
        timeout: timeOut,
        error: () => {
            // overTime()
        }

    })
    return data
}

function updateWorkstation(info, num = '') {

    info.plateNumber = num
    mui.showLoading("正在加载..", "div");
    $.ajax({
        url: `http://${ipValue}:55200/v1/workstation/update`,
        contentType: "application/json",
        data: JSON.stringify(info),
        type: "POST",
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                toastText('修改成功')
                setWorkInfo(getWorkstation(), plateNumber)
                localStorage.setItem('workstation', workstation);
                $(".tips-box .workstation").text(workstation)
                getWorkstationSite()
                workSite()
                mui.hideLoading();
            } else {
                toastText(res.msg)
                logout()
            }
        },
        timeout: timeOut,
        error: () => {
            overTime()
        }
    })

}

function setVehicleAllowedOrderTypes(url) {
    mui.showLoading("正在加载..", "div");
    $.ajax({
        url,
        contentType: "multipart/form-data",
        data: '',
        type: "POST",
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                localStorage.setItem('vehicles', vehicles);
                $(".tips-box .vehicles").text(vehicles)
                vehiclesinfo()
                setTimeout(mui.hideLoading(), 100)
                // $('.popup-box.popup-vehicle-info').hide()
            } else {
                toastText(res.msg)
                logout()
            }
        },
        timeout: timeOut,
        error: () => {
            overTime()
        }
    })

}

function locationType(type) {
    let arr = [],
        data = []
    $.ajax({
        url: `http://${ipValue}:55200/v1/locationType/${type}`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        dataType: "json",
        async: !workInfo,
        success: (res) => {
            if (res.code == 200) {
                arr = res.msg.allowedOperations
            } else {
                toastText(res.msg)
                logout()
            }
        },
        timeout: timeOut,
        error: () => {
            overTime()
        }
    })
    arr.map(item => {
        data.push({
            value: item,
            text: getChinese(item)
        })
    })
    return data
}

function getChinese(val) {
    let value = ''
    switch (val) {
        case 'Charging':
            value = '充电';
            break;
        case 'NOP':
            value = '无动作';
            break;
        case 'LOAD':
            value = '顶升';
            break;
        case 'Rotate':
            value = '旋转';
            break;
        case 'UNLOAD':
            value = '顶落';
            break;
    }
    return value
}

function getAllWorkstation() {
    let arr = []
    $.ajax({
        url: `http://${ipValue}:55200/v1/workstation/getAll`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        async: !workInfo,
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                arr = res.msg
                let index = arr.findIndex(checkWork)
                workstation = ''
                if (index > -1) {
                    workstation = arr[index].name
                }
                localStorage.setItem('workstation', workstation);
                $(".tips-box .workstation").text(workstation)
                workSite()
            }else{
				backErr(res.msg)
			}
        },
        timeout: timeOut,
        error: () => {
            // overTime()
        }
    })

    function checkWork(val) {
        return val.plateNumber == plateNumber
    }
}

function action(index) {
    if (index == actionIndex) {
        actionIndex = -1
        $.ajax({
            url: `http://${ipValue}:55200/v1/vehicle/stopmove/${vehiclesName}`,
            contentType: "multipart/form-data",
            params: vehiclesName,
            type: "post",
            dataType: "json",
            success: (res) => {
                toastText('停止成功')
                $('.new-btn-box .pattern-btn .second-box .btn-box').removeClass('active')
            },
            timeout: timeOut,
            error: () => {
                overTime()
            }
        })
    } else {
        actionIndex = index
        if (index > 1) {

        } else {

        }
        if (index == 0) {
            // 	前进
            // $.ajax({
            //     url: `http://${ipValue}:55200/v1/vehicle/forward/${vehiclesName}`,
            //     contentType: "multipart/form-data",
            //     params: vehiclesName,
            //     type: "post",
            //     dataType: "json",
            //     success: (res) => {
            //         toastText('开始前进')
            //     },
            //     timeout: timeOut,
            //     error: () => {
            //         overTime()
            //     }
            // })
        } else if (index == 1) {
            // 后退
            // $.ajax({
            //     url: `http://${ipValue}:55200/v1/vehicle/backoff/${vehiclesName}`,
            //     contentType: "multipart/form-data",
            //     params: vehiclesName,
            //     type: "post",
            //     dataType: "json",
            //     success: (res) => {
            //         toastText('开始后退')
            //     },
            //     timeout: timeOut,
            //     error: () => {
            //         overTime()
            //     }
            // })
        } else if (index == 2) {
            // 左横移
            $.ajax({
                url: `http://${ipValue}:55200/v1/vehicle/lefttraverse/${vehiclesName}`,
                contentType: "multipart/form-data",
                params: vehiclesName,
                type: "post",
                dataType: "json",
                success: (res) => {
                    toastText('开始左横移')
                },
                timeout: timeOut,
                error: () => {
                    overTime()
                }
            })
        } else if (index == 3) {
            // 左旋转
            $.ajax({
                //http://localhost:55200/v1/vehicle/leftrotation/Vehicle-01
                url: `http://${ipValue}:55200/v1/vehicle/leftrotation/${vehiclesName}`,
                contentType: "multipart/form-data",
                params: vehiclesName,
                type: "post",
                dataType: "json",
                success: (res) => {
                    toastText('开始左旋转')
                },
                timeout: timeOut,
                error: () => {
                    overTime()
                }
            })
        } else if (index == 4) {
            // 右横移/righttraverse/Vehicle-01
            $.ajax({
                url: `http://${ipValue}:55200/v1/vehicle/righttraverse/${vehiclesName}`,
                contentType: "multipart/form-data",
                params: vehiclesName,
                type: "post",
                dataType: "json",
                success: (res) => {
                    toastText('开始右横移')
                },
                timeout: timeOut,
                error: () => {
                    overTime()
                }
            })
        } else if (index == 5) {
            // 	右旋转
            $.ajax({
                url: `http://${ipValue}:55200/v1/vehicle/rightrotation/${vehiclesName}`,
                contentType: "multipart/form-data",
                params: vehiclesName,
                type: "post",
                dataType: "json",
                success: (res) => {
                    toastText('开始右旋转')
                },
                timeout: timeOut,
                error: () => {
                    overTime()
                }
            })
        }
    }
}

function getOrder(data) {
    // if (energyLevel < 20 || energyLevel == 20) {
    //     toastText('电量不足20%,请先充电')
    //     return false
    // }
    let param = {
			data: {
				"destinations": orderInfo  ,
				"deadline": new Date(accessTimeInAnHour()),
				"intendedVehicle":vehiclesName,
			},
			id: orderCode()
		}
	let arr = getLocations(),vehicleArr = getVehiclesinfo(),val={},point={},coordinate={},flag=false,hinder={}
	arr.map(item=>{
		if(item.name==orderInfo[0].locationName){
			point=item.attachedLinks[0].point
		}
	})
	pointsList.map(item=>{

		if(item.id == point.id){
			coordinate = item
		}
	})
	vehicleArr.map(item=>{
		if(coordinate.x && coordinate.y ){
			if(!item.name==vehiclesName){
				if(coordinate.x==item.precisePosition.x && coordinate.y==item.precisePosition.y){
					hinder=item
					flag=true
				}
			}

		}
	})

	if(flag){
		toastText(`车辆${hinder.name}停在${orderInfo[0].locationName},暂时无法去${orderInfo[0].locationName}工站`)
		return
	}
	mui.showLoading("正在加载..", "div");
	vehiclesType = 0
	rollIngOrder()
    $.ajax({
        url: `http://${ipValue}:55200/v1/transportOrders/${param.id} `,
        contentType: "application/json",
        data: JSON.stringify(param.data),
        type: "POST",
        dataType: "json",
        success: (res) => {
            workstationList = [
                []
            ]
            if (res.code == 200) {
                toastText('创建成功')
            } else {
				backErr(res.msg)
            }
			mui.hideLoading();
        },
        timeout: timeOut,
        error: () => {
            overTime()
			mui.hideLoading();
        }
    })
	//
}


/**
 * 获取地图上所有的点元素的信息
 */
function getPoints() {
    let arr = []
    $.ajax({
        url: `http://${ipValue}:55200/v1/points`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        async: !workInfo,
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                res.msg.map((item, index) => {
                    var val = {
                        x: item.position.x,
                        y: item.position.y,
                        z: item.position.z,
                        name: item.name,
                        type: item.type,
                        key: item.id,
                        id: item.id,
                        title: item.name,
                        parentType: 'points'
                    }
                    arr.push(val)

                })
                // drawPoints(pointsList)
                // getPaths()
                // locations()
                // this.locations()
                pointsList = arr
            } else {
				backErr(res.msg)
                // this.$message.warn(res.msg)
            }
        },
        timeout: timeOut,
        error: () => {
            // overTime()
        }
    })
    return arr
}

/**
 * 获取地图上所有路径元素的信息
 */
function getPaths() {
    $.ajax({
        url: `http://${ipValue}:55200/v1/paths`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        dataType: "json",
        success: (res) => {
            if (res.code == 200) {
                res.msg.map((item, index) => {
                    var val = {
                        name: item.name,
                        length: item.length,
                        routingCost: item.routingCost,
                        type: item.type,
                        id: item.id,
                        key: item.id,
                        title: item.name,
                        maxVelocity: item.maxVelocity,
                        maxReverseVelocity: item.maxReverseVelocity,
                        destinationPoint: item.destinationPoint,
                        sourcePoint: item.sourcePoint,
                        parentType: 'paths'
                    }
                    pathsList.push(val)
                    // this.drawPaths(pathsList)
                    // drawPaths( pathsList ,pointsList)
                })

            } else {
                // this.$message.warn(res.msg)
            }
        },
        timeout: timeOut,
        error: () => {
            overTime()
        }
    })
}

/**
 * 获取地图上所有location信息
 */
function getLocations() {
    let arr = []
    $.ajax({
        url: `http://${ipValue}:55200/v1/locations`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        dataType: "json",
        async: !workInfo,
        success: (res) => {
            if (res.code == 200) {
                arr = res.msg

            } else {
				backErr(res.msg)
                // this.$message.warn(res.msg)
            }
        },
        timeout: timeOut,
        error: () => {
            // overTime()
        }
    })
    return arr
}

function locations() {
    let arr = getLocations()
    arr.map((item) => {
        let attachedLinks = []
        if (item.attachedLinks && item.attachedLinks.length) {
            let pointInfo = {}
            item.attachedLinks.map(e => {
                pointsList.map(val => {
                    pointInfo = {}
                    if (e.point.id == val.id && e.point.name == val.name) {
                        pointInfo.x = val.x;
                        pointInfo.y = val.y;
                        pointInfo.name = val.name
                        attachedLinks.push(pointInfo)
                    }
                })
            })
        }
        val = {
            x: item.position.x,
            y: item.position.y,
            name: item.name,
            key: item.id,
            id: item.id,
            title: item.name,
            attachedLinks,
            parentType: 'locations',
            type: item.type
        }
        locationsList.push(val)

    })
}

function vehicleInfoShow() {
    let info = {}
    if (vehicles) {
        let arr = getVehiclesinfo()
        arr.map(item => {
            if (item.name === vehicles)
                info = item

        })
    } else {
        $('#android').html('')
        // return false
    }
    let vehiclesArr = getVehiclesinfo(),orderArr=[]
    vehiclesArr.map(item=>{
        if (item.transportOrder){
            vehiclesArr.push(item.transportOrder.name)
        }
    })
    if (vehiclesArr && vehiclesArr.length){
        setLine(vehiclesArr)
    }
    let val = '', headerInfo = ''
    loadState = info.loadState

    if (info.energyLevel > -1) {
        energyLevel = info.energyLevel
        let power = (info.energyLevel < 20) ? 'power' : ''
        val += `<div>电池电量：${info.energyLevel}%&nbsp;&nbsp;</div>`
        headerInfo += `<div>电池电量：${info.energyLevel}%&nbsp;&nbsp;</div>`
    }
    // emergencyState = info.emergencyState > 0 ? info.emergencyState.toString(2).padStart(8, '0').split("")
    //     .reverse() : []
    // console.log(emergencyState,8888)
    // if (emergencyState.length) {
    //     if (emergencyState[6] == 0) {
    //         $('.new-btn-box .stop-box').addClass('active')
    //     }
    //     if (emergencyState[6] == 1) {
    //         $('.new-btn-box .stop-box').removeClass('active')
    //     }
    // }
    emergencyState =info.emergencyState
    if (emergencyState ){
        $('.new-btn-box .stop-box').addClass('active')
    }else {
        $('.new-btn-box .stop-box').removeClass('active')
    }
    mui('.mui-switch')['switch']()
    if (info.controlModel) {
        headerInfo += ` <div>控制模式：自动&nbsp;&nbsp;</div>`
        val += ` <div>控制模式：自动&nbsp;&nbsp;</div>`
        if (controlModelSwitchFalg) {
            $('.switch-box .mui-switch').removeClass('mui-active')
        }

    } else {
        headerInfo += ` <div>控制模式：手动&nbsp;&nbsp;</div>`
        val += ` <div>控制模式：手动&nbsp;&nbsp;</div>`
        if (controlModelSwitchFalg) {
            $(".mui-switch-handle").attr("style", "");
            $('.switch-box .mui-switch').addClass('mui-active')
        }

    }
    // if (info.integrationLevel) {
    // 	val += ` <div>集成级别：${getLevel(info.integrationLevel)}&nbsp;&nbsp;</div>`
    // }
    if (info.closeLaserState == 0) {
        val += ` <div>四角避障：打开&nbsp;&nbsp;</div>`
    } else {
        val += ` <div>四角避障：屏蔽&nbsp;&nbsp;</div>`
    }
    if (vehicles) {
        chargingState = info.chargeState
        if (info.connectState) {
            val += ` <div>连接状态：已连接&nbsp;&nbsp;</div>`
        } else {
            val += ` <div>连接状态：已断开&nbsp;&nbsp;</div>`
        }
        if (info.state == 'UNAVAILABLE') {
            val += ` <div>状态：不可用&nbsp;&nbsp;</div>`
        } else if (info.state == 'ERROR') {
            val += ` <div>状态：错误&nbsp;&nbsp;</div>`
        } else if (info.state == 'IDLE') {
            val += ` <div>状态：空闲&nbsp;&nbsp;</div>`
        } else if (info.state == 'EXECUTING') {
            val += ` <div>状态：执行中&nbsp;&nbsp;</div>`
        } else if (info.state == 'CHARGING') {
            val += ` <div>状态：充电中&nbsp;&nbsp;</div>`
        } else {
            val += ` <div>状态：未知&nbsp;&nbsp;</div>`
        }
        if (info.chargeState == 0) {
            val += ` <div>充电状态：未知&nbsp;&nbsp;</div>`
        } else if (info.chargeState == 1) {
            val += ` <div>充电状态：正在充电&nbsp;&nbsp;</div>`
        } else if (info.chargeState == 3) {
            val += ` <div>充电状态：在桩未充电&nbsp;&nbsp;</div>`
        } else if (info.chargeState == 4) {
            val += ` <div>充电状态：异常&nbsp;&nbsp;</div>`
        } else {
            val += ` <div>充电状态：未充电&nbsp;&nbsp;</div>`
        }
    }

    if (info.currentPosition && info.currentPosition.name) {
        currentPositionId = info.currentPosition.name
        val += ` <div>位置：${info.currentPosition.name}&nbsp;&nbsp;</div>`
        headerInfo += ` <div>位置：${info.currentPosition.name}&nbsp;&nbsp;</div>`
    } else {
        currentPositionId = ""
        val += ` <div>位置： </div>`
    }
    if (info.transportOrder && info.transportOrder.name) {
        hasOrder = true
        orderNum = info.transportOrder.name
        val += `<div>订单编号：${info.transportOrder.name}</div>`
        headerInfo += `<div>订单编号：${info.transportOrder.name}</div>`
    } else {
        hasOrder = false
        orderNum = ''
        val += `<div>订单编号： </div>`
    }
    if (vehicles) {
        headerInfo += `<button>查看更多</button>`
    }
    $('#android').html(headerInfo)
    $('.vehicles-info-details').html(val)
}

function getWorkstationSite() {
    drawRect(getWorkstationSiteInfo())
}

function getWorkstationSiteInfo() {
    let data = getWorkstation(),
        locationsArr = getLocations(),
        linkArr = []

    locationsArr.map(item => {
        pointsList.map(e => {
            if (item.attachedLinks[0] && item.attachedLinks[0].point.name == e.name) {
                let info = {...e}
                info.siteName = item.name

                linkArr.push(info)
            }
        })
    })
    if (data && data.length && linkArr && linkArr.length) {
        data.map(item => {
            linkArr.map(e => {
                if (e.siteName == item.siteName) {
                   e.name=item.name
                }
            })
        })

    }
    return linkArr
}

//在地图上选择路线
function drawRect(data) {
    d3.selectAll(".workImg").remove();
    d3.selectAll(".workLine").remove();
    d3.selectAll(".workText").remove();
    svgInfo.workLine = []
    // if (data) {
    //     data.map(info => {
    //         if (typeof info.x=="undefined"){
    //
    //         }
    //         let x = -((!isNaN(info.x) ? (svgInfo.height + info.x / multiple) : (svgInfo.height)) + yOffset),
    //             y = (!isNaN(info.y) ? (info.y / multiple + svgInfo.width / 2) : (svgInfo.width / 2)) + yOffsetNew,
    //             orientationAngle = info.orientationAngle ? -info.orientationAngle : 0
    //         let workImgData = svgInfo.svg.append("g")
    //             .attr("fill", "#ffffff")
    //             .attr("class", "workImg")
    //             .append("image")
    //             .attr("xlink:href", workStationImg)
    //             .attr("x", x - 10)
    //             .attr("y", y - 28)
    //             .attr("width", 20)
    //             .attr("height",20)
    //             .attr('transform',
    //                 `rotate(${orientationAngle || 0},${x + xOffset} ,${y + yOffset})`)
    //             .attr("r", 30)
    //             // .attr()
    //             .attr("height", 50) //每个矩形的高度
    //             .on("click", function (d) {
    //                 return
    //                 if (hasOrder) {
    //                     toastText('当前车辆有订单,暂时无法创建新订单')
    //                     return false
    //                 }
    //                 // if (!workstation) {
    //                 //     toastText('请先添加工站')
    //                 //     return false
    //                 // }
    //                 if (!vehicles) {
    //                     toastText('请先添加车辆')
    //                     return false
    //                 }
    //                 let arr = [],
    //                     list = [],
    //                     picker = new mui.PopPicker(),
    //                     btnArray = ['是', '否'],
    //                     locationList = getLocations(),
    //                     type = ''
    //                 mui.confirm(`您确定添加${info.name}?`, '', btnArray, function (e) {
    //
    //                     if (e.index == 0) {
    //                         locationList.map(item => {
    //                             if (info.siteName === item.name) {
    //                                 type = item.type.name
    //                             }
    //                         })
    //                         list = locationType(type)
    //                         // 确认触发事件locationType(d.siteName)
    //                         list.map(e => {
    //                             arr.push({
    //                                 value: e.value,
    //                                 text: e.text
    //                             })
    //                         })
    //                         picker.setData(arr)
    //                         picker.show(function (selectItems) {
    //                             lineArr.push({
    //                                 "operation": selectItems[0].value,
    //                                 "locationName": info.siteName,
    //                                 text: selectItems[0].text,
    //                                 workstation: info.name
    //                             })
    //                             getOrderList(lineArr)
    //                         })
    //                     }
    //                 })
    //             }); //填充颜色
    //         // let lineVal = svgInfo.svg.append("line")
    //         //     .attr("x1", x - 30)
    //         //     .attr("y1", y - 6)
    //         //     .attr("x2", x )
    //         //     .attr("y2", y - 8 )
    //         //     .attr("class", "workLine")
    //         //     .attr("stroke", "rgb(255,113,1)")
    //         //     .style("stroke-dasharray", "2,2")
    //         //     .attr("stroke-width", 1)
    //         //     .attr("marker-end", "url(#arrow)")
    //         //
    //         // svgInfo.workLine.push(lineVal)
    //     })
    //
    //     // let text = svgInfo.svg.selectAll("g")
    //     //     .select("text")
    //     //     .data(data)
    //     //     .enter()
    //     //     .append("text")
    //     //     .text(function (d, e) {
    //     //         return d.name
    //     //     })
    //     //     .attr("class", "workText")
    //     //     .attr("x", function (info) { //每个矩形的起始y坐标
    //     //         return -((info.x ? (svgInfo.height + info.x / multiple) : (svgInfo.height)) + yOffset) - 60
    //     //     }) //每个矩形的起始x坐标
    //     //     .attr("y", function (info) { //每个矩形的起始y坐标
    //     //         return (info.y ? (info.y / multiple + svgInfo.width / 2) : (svgInfo.width / 2)) + yOffsetNew
    //     //     })
    //     //     .attr("font-size", 16)
    //     //     .attr("font-weight", 800)
    //     //     // .attr("fill", '#fff');
    //     //     .attr("fill", '#ff7200');
    //
    // }
}

//物料架在地图上
function drawRack(data) {
    data.map((item, index) => {
        getVehiclesinfo().map(e => {
            if (e.materialRackSerialNumber && e.materialRackSerialNumber == item
                .serialNumber) {
                data.splice(index, 1)
            }
        })
    })
    d3.selectAll(".rackImg").remove();
    d3.selectAll(".rackText").remove();
    if (data) {
        data.map(info => {
            let x = info.coordinates_y ? (info.coordinates_y / multiple + svgInfo.width / 2) :
                    svgInfo.width / 2,
                y = info.coordinates_x ? (svgInfo.height + (info.coordinates_x) / multiple) :
                    svgInfo.height,
                orientationAngle = info.orientationAngle ? -info.orientationAngle : 0
            let workImgData = svgInfo.svg.append("g")
                .attr("fill", "#ffffff")
                .attr("class", "rackImg")
                .append("image")
                .attr("xlink:href", rackImg)
                .attr("x", x + xOffset - 24)
                .attr("y", y + yOffset - 20)
                .attr("width", 40)
                .attr("r", 105)
                .attr("height", 40) //每个矩形的高度
                .attr("height", 40) //每个矩形的高度
        })
        //


        text = svgInfo.svg.selectAll("g")
            .select("text")
            .data(data)
            .enter()
            .append("text")
            .text(function (d, e) {
                return d.serialNumber
            })
            .attr("class", "rackText")
            .attr("x", function (info) { //每个矩形的起始y坐标
                return (info.coordinates_y ? (info.coordinates_y / multiple + svgInfo.width / 2) : (
                    svgInfo.width / 2)) + xOffset - 25
            }) //每个矩形的起始x坐标
            .attr("y", function (info) { //每个矩形的起始y坐标
                return (info.coordinates_x ? (svgInfo.height + info.coordinates_x / multiple) : (
                    svgInfo.height)) + yOffset - 45
            })
            .attr("font-size", 20)
            .attr("fill", '#00d9ff');
    }
}


// 当前工站位置
function workSite() {
    getWorkstation().map(item => {
        if (workstation == item.name) {

            getLocations().map(_item => {
                if (item.siteName === _item.name) {
                    pointsList.map(e => {
                        if (_item.attachedLinks[0] && e.name == _item
                            .attachedLinks[0].point.name) {
                            drawSite(e)
                        }
                    })
                }
            })
        }
    })
}

function setIntervalFunction() {
    runId = 0
    $.ajax({
        url: `http://${ipValue}:55200/v1/network/ping`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        dataType: "json",
        timeout: 3000,
        success: (res) => {
            if (res.code == 200) {
                workInfo = true
                runId = 1
                getInfo()
                $('.no-wet').hide()
            } else {
                $('.no-wet').show()
                clearPromiseInterval(timing)
                clearInterval(timing)
                window.location.href = 'poorNetwor.html'
            }
        },
        error: () => {
            netLess()
            clearPromiseInterval(timing)
            clearInterval(timing)
            window.location.href = 'poorNetwor.html'
        }
    })
}


function vehiclesinfo() {
    setVehicleInfo(getVehiclesinfo(), workstation)
}

function overTime() {
    workInfo = false
    clearPromiseInterval(timing)
    clearInterval(timing)
    runId = 0
    mui.confirm('网络错误，请检查网络或者IP是否正确', '提示', ['取消', '确认'], function(e) {

    	if (e.index == 1) {
    		// mui.toast('确认');
    	} else {
    		// mui.toast('取消');
    	}
    	// noNet()
    })
    return false
}

var timeOut5 = 10 * 60 * 1000; //设置超时时间
var currentTime = new Date().getTime(); //当前时间
var compareTime = new Date().getTime(); //对比时间
$(".box").on("touchstart", function () {
})
$(".box").on("touchend", function () {
    resetTime()
})

//对比时间重置
function resetTime() {
    compareTime = new Date().getTime();
}

//超时检查
function checkTime() {
    currentTime = new Date().getTime();
    if (currentTime - compareTime > timeOut5) {
        window.location.reload()
        // #ifdef APP-PLUS
        plus.runtime.restart()
        // #endif
        window.location = 'index.html';

        resetTime()
        return;
    }
}

function inter() {
    checkTime()
    if (runId) {
        $.ajax({
            url: `http://${ipValue}:55200/v1/network/ping`,
            contentType: "multipart/form-data",
            data: '',
            type: "get",
            dataType: "json",
            timeout: 3000,
            success: (res) => {
                if (res.code == 200) {
                    per()
                    $('.no-wet').hide()
                } else {
                    runId = 0
                    overTime()
                    clearPromiseInterval(timing)
                    clearInterval(timing)
                    setIntervalFunction()
                    netLess()
                }
            },
            error: function () {
                runId = 0
                //查看错误信息
                clearPromiseInterval(timing)
                clearInterval(timing)
                setIntervalFunction()
                overTime()
                netLess()
                // window.location.href = 'poorNetwor.html'
            }
        })
    } else {
        clearPromiseInterval(timing)
        clearInterval(timing)
        setIntervalFunction()
        netLess()
        // window.location.href = 'poorNetwor.html'
        // overTime()
    }
}

function per() {
    vehicleInfoShow()
    getvehiclesSeit()
    // setLine()
}

// 检测ip网络
function ping() {
    mui.showLoading("数据加载中..", "div");
    $.ajax({
        url: `http://${ipValue}:55200/v1/network/ping`,
        contentType: "multipart/form-data",
        data: '',
        type: "get",
        dataType: "json",
        timeout: 3000,
        success: (res) => {
            if (res.code == 200) {
				// login('manager',123456)
				login()
				// login('admin02',123456)
				 // login('23',123456)
				 // login('admin201',123456)
                // workInfo = true
                // getInfo()
                // mui.hideLoading(); //隐藏后的回调函数
                // $('.new-popup').hide()
                // runId = 1
            } else {
                // err()
                // netLess()
				backErr(res.msg)
            }
        },
        error: function () {
            //查看错误信息
            err()
            netLess()
        }
    })

}
// 登录
function login( user='worker',pwd="123456" ) {
    $.ajax({
        url: `http://${ipValue}:55200/v1/user/login?user_code=${user}&user_pwd=${pwd}`,
        contentType: "multipart/form-data",
        data: '',
        type: "post",
        dataType: "json",
        timeout: 3000,
        success: (res) => {
            if (res.code == 200) {
                workInfo = true
                getInfo()
                mui.hideLoading(); //隐藏后的回调函数
                $('.new-popup').hide()
                runId = 1
            } else {
				backErr(res.msg)
                // err()
                // netLess()
            }
        },
        error: function () {
            //查看错误信息
            err()
            netLess()
        }
    })

}

function setIp() {
    let value = ipValue || '请输入正确的IP地址'

    $('#ipInput').val(value)
    $('.new-ip-popup').show()
    //输入框失去焦点
    // document.querySelector('.mui-popup-input').firstChild.blur()
    //默认值设置
    // document.querySelector('.mui-popup-input').firstChild.value = ipValue

}

function err() {
    //
    toastText('网络连接不可用,请确定网络连接,或者请输入正确ip')
    setIp()
    workInfo = false
    clearPromiseInterval(timing)
    clearInterval(timing)
    runId = 0
    mui.hideLoading(); //隐藏后的回调函数
    return false
}

function netLess() {
    $('.no-wet').show()
    //
    return false
}

function backErr(msg) {
	toastText(msg)
}

function getInfo() {
    $(".tips-box .workstation").text(workstation)
    $(".tips-box .vehicles").text(vehicles)
    /*行驶路线*/
    // drawRect(workData)

    // getvehiclesSeit()
    /*当前位置*/
    // getWorkstationSite()
    justOnce()
    // workSite()
    inter()
    timing = setPromiseInterval(inter, 500)
    // timing = setInterval(() => {
    // 	setTimeout(inter, 0)
    // }, 1000);
}

function justOnce(){
    getWorkTypes()
    getWorkStationArr()
    getPoints()
    vehiclesinfo()
    locations()
    getAllWorkstation()
    drawRack(getAllRackInfo())
    //  地图画点
    // drawSport(getPoints())
    // 画工站
    getWorkstationSite()
	rollIngOrder()
}
let timeoutRollIng= null
function rollIngOrder(){
	rollIng()
	clearInterval(timeoutRollIng)
	timeoutRollIng= null
	timeoutRollIng = setInterval(rollIng,30*1000)
}
function getWorkTypes(){

    $.ajax({
        url: `http://${ipValue}:55200/v1/locationTypes`,
        contentType: "application/json",
        params: '',
        type: "get",
        dataType: "json",
        success: (res) => {
            locationTypeArr = []
            if (res.code==200){
                if (res.msg && res.msg.length){
                    res.msg.map(item=>{
                        let list =[]
                        if (item.allowedOperations && item.allowedOperations.length){
                            item.allowedOperations.map(e=>{
                                list.push({
                                    value: e,
                                    text: getChinese(e)

                                })
                            })
                        }

                        locationTypeArr.push({
                            type:item.name,
                            list
                        })
                    })
                }
            }else{
				backErr(res.msg)
			}
        },
        timeout: timeOut,
        error: () => {
            overTime()
        }
    })
}
function switchFalgToTrue() {
    mui.hideLoading();
    switchFalg = true
    controlModelSwitchFalg = true
    timing = setPromiseInterval(inter, 1000)
    // timing = setInterval(() => {
    // 	setTimeout(inter, 0)
    // }, 1000);
}

$('.popup-selectVehicles .popup-select-footer .config').click(function(){
	vehiclesType=0
	$('.new-btn-box .btn-list .pattern-btn').eq(0).addClass('active')
	$('.new-btn-box .btn-list .pattern-btn').eq(1).removeClass('active')
	$('.new-btn-box .pattern-box .pattern-list').eq(0).addClass('active')
	$('.new-btn-box .pattern-box .pattern-list').eq(1).removeClass('active')
})
